package com.siyoumi.app.test.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.siyoumi.app.rabbitmq.RabbitMqMessage;
import com.siyoumi.app.rabbitmq.RabbitMqPublishAbs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

//死信 发送消息
@Slf4j
public class RabbitMqPublishDead
        extends RabbitMqPublishAbs {
    @Override
    protected String getExchangeName() {
        return "dead_exchange";
    }

    @Override
    protected String getQueueName() {
        return "dead_queue";
    }

    static public RabbitMqPublishAbs getIns() {
        RabbitMqPublishAbs mq = new RabbitMqPublishDead();
        mq.init();
        return mq;
    }

    @SneakyThrows
    @Override
    public void init() {
        super.init();

        getChannel().exchangeDeclare(getExchangeName(), BuiltinExchangeType.TOPIC, true, false, null);
        getChannel().queueDeclare(getQueueName(), true, false, false, null);
        getChannel().queueBind(getQueueName(), getExchangeName(), "abc.#");

        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", getExchangeName());
        args.put("x-dead-letter-routing-key", "abc.abc");
        args.put("x-max-length", 2); //设置队列最大长度

        getChannel().queueDeclare("dead_queue_x", true, false, true, args);
        getChannel().queueBind("dead_queue_x", "def_exchange", "");
    }

    @Override
    @SneakyThrows
    public void publishMessage(RabbitMqMessage message) {
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .deliveryMode(2) //消息持久化
                .build();

        getChannel().basicPublish("def_exchange", message.getRoutingKey(), properties, message.getContent().getBytes());
    }
}